<script setup lang="ts">
import type { AreaVO } from '#/api/system/area/model';

import { computed, onMounted, ref, watch } from 'vue';

import { Cascader } from 'ant-design-vue';

import { useAreaStore } from '#/store/modules/area';

const props = defineProps({
  placeholder: {
    type: String,
    default: '请选择省/市/区',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否只需要选择到市级
  cityOnly: {
    type: Boolean,
    default: false,
  },
  // 省份ID
  provinceId: {
    type: [String, Number],
    default: undefined,
  },
  // 城市ID
  cityId: {
    type: [String, Number],
    default: undefined,
  },
  // 区县ID
  districtId: {
    type: [String, Number],
    default: undefined,
  },
});

const emit = defineEmits([
  'change',
  'update:provinceId',
  'update:cityId',
  'update:districtId',
]);

// 使用地区数据存储
const areaStore = useAreaStore();
const isLoading = ref(false);

// 级联选择器的值
const cascaderValue = ref<(number | string)[]>([]);

// 加载地区数据
onMounted(async () => {
  console.log('组件挂载，开始加载数据');
  console.log('初始props值:', {
    provinceId: props.provinceId,
    cityId: props.cityId,
    districtId: props.districtId,
  });

  isLoading.value = true;
  try {
    await areaStore.loadAreaData();
    console.log('地区数据加载完成');
  } finally {
    isLoading.value = false;
  }

  // 初始化级联选择器的值
  initCascaderValue();
  console.log('初始化后的cascaderValue:', cascaderValue.value);
});

// 监听单独的省市区ID变化
watch(
  [() => props.provinceId, () => props.cityId, () => props.districtId],
  () => {
    console.log('省市区ID变化:', {
      provinceId: props.provinceId,
      cityId: props.cityId,
      districtId: props.districtId,
    });
    initCascaderValue();
    console.log('ID变化后的cascaderValue:', cascaderValue.value);
  },
  { deep: true },
);

// 初始化级联选择器的值
function initCascaderValue() {
  const values = [];
  if (props.provinceId) {
    values.push(props.provinceId);
  }
  if (props.cityId) {
    values.push(props.cityId);
  }
  if (!props.cityOnly && props.districtId) {
    values.push(props.districtId);
  }
  console.log('构建的values数组:', values);
  cascaderValue.value = values;
}

// 构建级联数据
const cascaderOptions = computed(() => {
  // 直接从省份开始
  return buildProvinceOptions(areaStore.provinces);
});

// 构建省份选项
function buildProvinceOptions(provinces: AreaVO[]) {
  return provinces.map((province) => {
    const cities = areaStore.cities(province.id);
    return {
      value: province.id,
      label: province.name,
      children: cities.map((city) => {
        // 如果只需要选择到市级，则不添加区县选项
        if (props.cityOnly) {
          return {
            value: city.id,
            label: city.name,
          };
        }

        const districts = areaStore.districts(city.id);
        return {
          value: city.id,
          label: city.name,
          children: districts.map((district) => ({
            value: district.id,
            label: district.name,
          })),
        };
      }),
    };
  });
}

// 处理选择变化
function handleChange(value: any[] | string, selectedOptions: any) {
  console.log('选择变化:', value, selectedOptions);
  // 分别更新省市区的值
  const len = value.length;
  if (len >= 1) emit('update:provinceId', value[0]);
  if (len >= 2) emit('update:cityId', value[1]);
  if (len >= 3 && !props.cityOnly) emit('update:districtId', value[2]);

  emit('change', value, selectedOptions);
}
</script>

<template>
  <Cascader
    v-model="cascaderValue"
    :options="cascaderOptions"
    :placeholder="placeholder"
    :disabled="disabled"
    change-on-select
    @change="handleChange"
    :loading="isLoading"
  />
</template>
